/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipti.br.tag.dao;

import org.ipti.br.tag.entity.Grants;
import org.ipti.br.tag.entity.Functionality_;
import org.ipti.br.tag.entity.Grants_;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.ipti.br.tag.util.EncryptionUtil;

/**
 *
 * @author israel
 */
@Stateless
public class GrantsFacade extends AbstractFacade<Grants> {

    @PersistenceContext(unitName = "TAG2PU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public GrantsFacade() {
        super(Grants.class);
    }

    @Override
    public void create(Grants grants) {
        getEntityManager().persist(grants);
    }

    @Override
    public void edit(Grants grants) {
        grants.setSerialNumber(null);

        getEntityManager().merge(grants);
    }
    
    public void editForSynchronization(Grants grants) {
        getEntityManager().merge(grants);
    }

    public List<Grants> grantsPerPersonage(Long personageID) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Grants> cq = cb.createQuery(Grants.class);
        Root<Grants> from = cq.from(Grants.class);
        Predicate[] predicateList = new Predicate[2];
        predicateList[0] = cb.equal(from.get(Grants_.personageID), personageID);
        predicateList[1] = cb.isNull(from.get(Grants_.actorID));
        cq.where(cb.and(predicateList));

        return getEntityManager().createQuery(cq).getResultList();
    }

    public boolean grantsExistForPersonageFunc(Long personageID, Long functionalityID) { //TODO: Responder ainda na consulta ao SGBD
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Grants> cq = cb.createQuery(Grants.class);
        Root<Grants> from = cq.from(Grants.class);
        Predicate[] predicateList = new Predicate[2];
        predicateList[0] = cb.equal(from.get(Grants_.personageID), personageID);
        predicateList[1] = cb.isNull(from.get(Grants_.actorID));
        predicateList[1] = cb.equal(from.get(Grants_.functionality).get(Functionality_.id), functionalityID);
        cq.where(cb.and(predicateList));

        return (!getEntityManager().createQuery(cq).getResultList().isEmpty());
    }
}
